<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>学生列表</title>
<script type="text/javascript" src="js/jquery-1.12.4.js"></script>
<script type="text/javascript">
	$(function(){
		getGrade();
		getPageStudent();
	})
	
	function getGrade(){
		$.getJSON("grade/all",function(res){
			//console.log(res)
			var array = res.data;
			for(var i in array){
				//console.log(array[i])
				$("#gid").append(`
						<option value="${array[i].id}">
						${array[i].gradename}
						</option>`)
			}
		})
	}
	
	//当前页数
	var current =0;
	//总页数
	var pages =0;
	//年级编号
	var gid =0;
	//每页行数
	var pageRows =3;
	
	function getPageStudent(){
		$.getJSON("stu/page",{"pageIndex":current,"gid":gid,"pageRows":pageRows},function(res){
			current = res.data.current
			pages = res.data.pages
		 	$("#current") .text(current)
		 	$("#pages") .text(pages)
			var stus = res.data.records; 
			$("#tbody").empty()
			for(var i in stus){
				var stu = stus[i]
				$("#tbody").append(`
					<tr>
						<td>${stu.id}</td>
						<td>${stu.name}</td>
						<td>${stu.age}</td>
						<td>${stu.grade.gradename}</td>
						<td>
							<button onclick="edit(${stu.id})">编辑</button>
							<button onclick="del(${stu.id})">删除</button>
						</td>
					</tr>`)
			}
		})
	}
	
	function getFirst(){
		current = 1;
		getPageStudent()
	}
	
	function getLast(){
		current = pages;
		getPageStudent()
	}
	
	function getPre(){
		if(current==1){
			return;
		}
		current--
		getPageStudent()
	}
	
	function getNext(){
		if(current==pages){
			return;
		}
		current++
		getPageStudent()
	}
	
	function abc(){
		current=1
		gid = $("#gid").val()
		getPageStudent()
	}
	
	function changePageRows(){
		current=1
		pageRows = $("#pageRows").val()
		getPageStudent()
	}
	
	function del(id){
		var falg = confirm("确认要删除吗？")
		if(!falg){
			return;
		}
		//alert(id)
		//异步删除
		$.getJSON("stu/delete",{"id":id},function(res){
			if(res.resultCode==200){
				//异步的加载当前页数据
				getPageStudent()
			}else{
				alert("删除失败")
			}
		})
	}
	
	function edit(id){
		location.href="edit.html?id="+id;
	}
	
	
</script>
</head>
<body>
	<a href="edit.html">新增学生</a>
	<div>
		<form action="/stu/page" method="get" onchange="abc()">
			年级：<select name="gid" id="gid">
			<option value="0">全部</option>
			</select>
		</form>
	</div>
	<table width="600" border="1" >
		<thead>
			<tr>
				<th>编号</th>
				<th>姓名</th>
				<th>年龄</th>
				<th>所在年级</th>
				<th>操作</th>
			</tr>
		</thead>
		<tbody id="tbody">
		</tbody>
	</table>
	<p>
		<button onclick="getFirst()">首页</button>
		<button onclick="getPre()">上一页</button>
		<button onclick="getNext()">下一页</button>
		<button onclick="getLast()">尾页</button>
		第<span id="current">0</span>页/
		共<span id="pages">1</span>页
	</p>
	<p>
		每页行数: <select id="pageRows" onchange="changePageRows()">	
				<option selected
					value="3">3</option>
			
				<option 
					value="5">5</option>
			
				<option 
					value="9">9</option>
		</select>
	</p>
</body>
</html>